<template>
  <div class="product-detail-container">
    <a-card>
      <!-- 固定在卡片头部的返回按钮 -->
      <template #title>
        <a-space>
          <a-button @click="router.back()">
            <template #icon><left-outlined /></template>
            返回
          </a-button>
          <span class="page-title">商品详情</span>
        </a-space>
      </template>

      <!-- 内容区域 -->
      <div class="content-wrapper">
        <!-- 基本信息 -->
        <a-descriptions bordered :column="2">
          <a-descriptions-item label="商品图片" :span="2">
            <img :src="productInfo.image" alt="商品图片" style="width: 200px; height: 200px; object-fit: cover;" />
          </a-descriptions-item>
          <a-descriptions-item label="商品名称">{{ productInfo.name }}</a-descriptions-item>
          <a-descriptions-item label="商品状态">
            <a-tag :color="productInfo.status === PRODUCT_STATUS.ACTIVE ? 'success' : 'default'">
              {{ PRODUCT_STATUS_TEXT[productInfo.status] }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="商品分类">
            <a-space>
              {{ getCategoryName(productInfo.categoryId) }}
              <a-button v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER" type="link" @click="handleEdit">编辑</a-button>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item label="总销量">{{ productInfo.sales }}</a-descriptions-item>
          <a-descriptions-item label="最低价格">¥{{ productInfo.minPrice }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatDateTime(productInfo.createTime) }}</a-descriptions-item>
          <a-descriptions-item label="商品描述" :span="2">{{ productInfo.description }}</a-descriptions-item>
        </a-descriptions>

        <!-- 规格列表 -->
        <a-divider>
          <a-space>
            规格列表
            <a-button v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER" type="primary" @click="handleAddSku">新增规格</a-button>
          </a-space>
        </a-divider>

        <a-table
          :columns="skuColumns"
          :data-source="productInfo.productSKUVOList"
          :pagination="false"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'image'">
              <img :src="record.image" alt="规格图片" style="width: 50px; height: 50px" />
            </template>
            <template v-if="column.key === 'price'">
              ¥{{ record.price }}
            </template>
            <template v-if="column.key === 'status'">
              <a-tag :color="record.status === PRODUCT_STATUS.ACTIVE ? 'success' : 'default'">
                {{ PRODUCT_STATUS_TEXT[record.status] }}
              </a-tag>
            </template>
            <template v-if="column.key === 'auditStatus'">
              <a-tag :color="getAuditStatusColor(record.auditStatus)">
                {{ getAuditStatusText(record.auditStatus) }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <!-- 农户可以编辑、上架下架、删除 -->
                <template v-if="userStore.userInfo?.userRole === USER_ROLE.FARMER">
                  <a-button type="link" @click="handleEditSku(record)">编辑</a-button>
                  <a-button
                    type="link"
                    @click="handleToggleSkuStatus(record)"
                  >
                    {{ record.status === PRODUCT_STATUS.ACTIVE ? '下架' : '上架' }}
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个规格吗？"
                    @confirm="handleDeleteSku(record)"
                  >
                    <a-button type="link" danger>删除</a-button>
                  </a-popconfirm>
                </template>
                <!-- 管理员只能审核和查看 -->
                <template v-else-if="userStore.userInfo?.userRole === USER_ROLE.ADMIN">
                  <a-button
                    v-if="record.auditStatus === AUDIT_STATUS.PENDING"
                    type="link"
                    @click="handleAuditSku(record)"
                  >
                    审核
                  </a-button>
                  <a-button
                    v-else-if="record.auditStatus === AUDIT_STATUS.APPROVED"
                    type="link"
                    @click="handleAuditSku(record)"
                  >
                    重新审核
                  </a-button>
                  <a-button
                    v-else-if="record.auditStatus === AUDIT_STATUS.REJECTED"
                    type="link"
                    @click="handleAuditSku(record)"
                  >
                    重新审核
                  </a-button>
                </template>
              </a-space>
            </template>
          </template>
        </a-table>

        <!-- 评论列表 -->
        <a-divider>商品评论</a-divider>
        <a-list
          :data-source="reviewList"
          :pagination="reviewPagination"
          @change="handleReviewPageChange"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-comment
                :author="item.userName"
                :avatar="item.userAvatar"
                :content="item.content"
                :datetime="formatDateTime(item.createTime)"
              >
                <template #actions>
                  <span>评分：{{ item.rating }}分</span>
                  <span>规格：{{ item.skuName }}</span>
                </template>
              </a-comment>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </a-card>

    <!-- 编辑商品弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      title="编辑商品"
      @ok="handleModalOk"
    >
      <a-form
        :model="productForm"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="商品名称" name="name">
          <a-input v-model:value="productForm.name" />
        </a-form-item>
        <a-form-item label="商品分类" name="categoryId">
          <a-select v-model:value="productForm.categoryId">
            <a-select-option v-for="item in categories" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="商品图片" name="image">
          <upload-image
            v-model:value="productForm.image"
            :biz="BIZ_TYPE.PRODUCT_IMG"
          />
        </a-form-item>
        <a-form-item label="商品描述" name="description">
          <a-textarea
            v-model:value="productForm.description"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑规格弹窗 -->
    <a-modal
      v-model:visible="skuModalVisible"
      :title="skuModalTitle"
      @ok="handleSkuModalOk"
    >
      <a-form
        :model="skuForm"
        :rules="skuRules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="规格名称" name="quantity">
          <a-input v-model:value="skuForm.quantity" placeholder="如：大份、中份、小份" />
        </a-form-item>
        <a-form-item label="规格图片" name="image">
          <upload-image
            v-model:value="skuForm.image"
            :biz="BIZ_TYPE.PRODUCT_SPEC_IMG"
          />
        </a-form-item>
        <a-form-item label="价格" name="price">
          <a-input-number
            v-model:value="skuForm.price"
            :min="0"
            :precision="2"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="库存" name="stock">
          <a-input-number
            v-model:value="skuForm.stock"
            :min="0"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="skuForm.description"
            :rows="4"
            placeholder="请输入规格描述"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 审核弹窗 -->
    <a-modal
      v-model:visible="auditModalVisible"
      title="审核商品规格"
      @ok="handleAuditSubmit"
    >
      <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="规格名称">
          {{ currentSku?.quantity }}
        </a-form-item>
        <a-form-item label="价格">
          ¥{{ currentSku?.price }}
        </a-form-item>
        <a-form-item label="审核结果" name="auditStatus">
          <a-radio-group v-model:value="auditForm.auditStatus">
            <a-radio :value="AUDIT_STATUS.APPROVED">通过</a-radio>
            <a-radio :value="AUDIT_STATUS.REJECTED">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { LeftOutlined } from '@ant-design/icons-vue'
import { getProductVoByIdUsingGet, updateProductUsingPost } from '@/api/productController'
import { getProductReviewVoByIdUsingPost } from '@/api/productReviewController'
import { listCategoryByPageUsingPost, listCategoryVoByPageUsingPost } from '@/api/categoryController'
import { PRODUCT_STATUS, PRODUCT_STATUS_TEXT } from '@/constants/product'
import { PRODUCT_STATUS as AUDIT_STATUS, PRODUCT_STATUS_TEXT as AUDIT_STATUS_TEXT } from '@/constants/audit'
import { BIZ_TYPE } from '@/constants/upload'
import { formatDateTime } from '@/utils/format'
import UploadImage from '@/components/UploadImage.vue'
import {
  addProductSkuUsingPost,
  updateProductSkuUsingPost,
  deleteProductSkuUsingPost, auditProductSkuUsingPost
} from '@/api/productSkuController'
import { getProductSkuvoByIdUsingGet } from '@/api/productSkuController'
import { useUserStore } from '@/stores/user'
import { USER_ROLE } from '@/constants/user'

const router = useRouter()
const route = useRoute()
const productId = route.params.id as string
const userStore = useUserStore()

// 商品信息
const productInfo = ref<API.ProductVO>({})

// 评论列表
const reviewList = ref<API.ProductReviewVO[]>([])
const reviewPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 规格表格列
const skuColumns = [
  {
    title: '规格图片',
    key: 'image',
    width: 100
  },
  {
    title: '规格名称',
    dataIndex: 'quantity',
    key: 'quantity'
  },
  {
    title: '价格',
    key: 'price',
    width: 100
  },
  {
    title: '销量',
    dataIndex: 'sales',
    key: 'sales',
    width: 100,
    customRender: ({ text }: { text: number | undefined }) => text || 0
  },
  {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock',
    width: 100
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '审核状态',
    key: 'auditStatus',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

// 分类列表
const categories = ref<API.CategoryVO[]>([])

// 编辑表单
const modalVisible = ref(false)
const productForm = ref<API.ProductUpdateRequest>({
  id: undefined,
  name: '',
  categoryId: undefined,
  image: '',
  description: '',
  status: PRODUCT_STATUS.ACTIVE
})

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入商品名称' }],
  categoryId: [{ required: true, message: '请选择商品分类' }]
}

// 规格表单
const skuModalVisible = ref(false)
const skuModalTitle = ref('')
const skuForm = ref<API.ProductSKUAddRequest | API.ProductSKUUpdateRequest>({
  productId: Number(productId),
  quantity: '',
  price: 0,
  stock: 0,
  image: '',
  description: ''
})

// 规格表单规则
const skuRules = {
  quantity: [{ required: true, message: '请输入规格名称' }],
  price: [{ required: true, message: '请输入价格' }],
  stock: [{ required: true, message: '请输入库存' }]
}

// 审核弹窗
const auditModalVisible = ref(false)
const currentSku = ref<any>(null)
const auditForm = ref({
  auditStatus: AUDIT_STATUS.APPROVED
})

// 获取商品信息
const fetchProductInfo = async () => {
  try {
    const res = await getProductVoByIdUsingGet({ id: Number(productId) })
    productInfo.value = res.data

  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 获取评论列表
const fetchReviewList = async () => {
  try {
    const res = await getProductReviewVoByIdUsingPost({
      productId: Number(productId)
    })
    reviewList.value = res.data
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 评论分页变化
const handleReviewPageChange = (page: number) => {
  reviewPagination.value.current = page
  fetchReviewList()
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await listCategoryVoByPageUsingPost({
      pageSize: 40,
      current: 1
    })
    categories.value = res.data.records
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 获取分类名称
const getCategoryName = (categoryId: number | undefined) => {
  if (!categoryId) return '-'
  const category = categories.value.find(item => item.id === categoryId)
  return category?.name || '-'
}

// 编辑商品
const handleEdit = () => {
  productForm.value = {
    id: productInfo.value.id,
    name: productInfo.value.name,
    categoryId: productInfo.value.categoryId,
    image: productInfo.value.image,
    description: productInfo.value.description,
    status: productInfo.value.status
  }
  modalVisible.value = true
}

// 保存商品
const handleModalOk = async () => {
  try {
    await updateProductUsingPost(productForm.value)
    message.success('更新成功')
    modalVisible.value = false
    fetchProductInfo()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 新增规格
const handleAddSku = () => {
  skuModalTitle.value = '新增规格'
  skuForm.value = {
    productId: Number(productId),
    quantity: '',
    price: 0,
    stock: 0,
    image: '',
    description: ''
  }
  skuModalVisible.value = true
}

// 编辑规格
const handleEditSku = (record: any) => {
  skuModalTitle.value = '编辑规格'
  skuForm.value = { ...record }
  skuModalVisible.value = true
}

// 保存规格
const handleSkuModalOk = async () => {
  try {
    const api = skuForm.value.id ? updateProductSkuUsingPost : addProductSkuUsingPost
    await api(skuForm.value)
    message.success(`${skuModalTitle.value}成功`)
    skuModalVisible.value = false
    fetchProductInfo()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 删除规格
const handleDeleteSku = async (record: any) => {
  try {
    await deleteProductSkuUsingPost({
      id: record.id
    })
    message.success('删除成功')
    fetchProductInfo()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 切换规格状态
const handleToggleSkuStatus = async (record: any) => {
  try {
    await updateProductSkuUsingPost({
      ...record,
      status: record.status === PRODUCT_STATUS.ACTIVE ? PRODUCT_STATUS.INACTIVE : PRODUCT_STATUS.ACTIVE
    })
    message.success('操作成功')
    fetchProductInfo()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

// 获取审核状态颜色
const getAuditStatusColor = (auditStatus: string) => {
  if (auditStatus === AUDIT_STATUS.APPROVED) return 'success'
  if (auditStatus === AUDIT_STATUS.REJECTED) return 'error'
  return 'default'
}

// 获取审核状态文本
const getAuditStatusText = (auditStatus: string) => {
  if (auditStatus === AUDIT_STATUS.APPROVED) return '已审核'
  if (auditStatus === AUDIT_STATUS.REJECTED) return '已拒绝'
  return '待审核'
}

// 审核规格
const handleAuditSku = (record: any) => {
  // 实现审核逻辑
  currentSku.value = record
  auditModalVisible.value = true
}

// 审核提交
const handleAuditSubmit = async () => {
  try {
    await auditProductSkuUsingPost({
      id:currentSku.value.id,
      auditStatus: auditForm.value.auditStatus
    })
    message.success('审核成功')
    auditModalVisible.value = false
    fetchProductInfo()
  } catch (error) {
    // 错误处理由拦截器统一处理
  }
}

onMounted(() => {
  fetchCategories()
  fetchProductInfo()
  fetchReviewList()
})
</script>

<style scoped>
.product-detail-container {
  padding: 24px;
  background: #f0f2f5;
}

.page-title {
  font-size: 16px;
  font-weight: 500;
}

.content-wrapper {
  margin-top: 16px;
}

:deep(.ant-descriptions) {
  margin-bottom: 24px;
}

:deep(.ant-table-wrapper) {
  margin-bottom: 24px;
}
</style>
